package com.erp.activity

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.PointF
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.provider.MediaStore
import android.view.MotionEvent
import android.view.View
import android.widget.AdapterView
import android.widget.ListView
import android.widget.TextView
import com.erp.MyCamera.CameraActivity
import com.erp.R
import com.erp.bean.PhotoProcess
import com.erp.bean.ProdyctionClientBean
import com.erp.module.crm.xXCrm.FragmentClientfive
import com.erp.myAdapter.XGAdapter
import com.erp.util.Httputil
import com.erp.util.Myutil
import kotlinx.android.synthetic.main.activity_danjuiv.*
import kotlinx.android.synthetic.main.header_knoya1.*
import org.xutils.common.Callback
import org.xutils.image.ImageOptions
import org.xutils.x
import java.util.*

/**
 * Created by Administrator on 2016/11/28/028.
 * 作者：刘洋
 */
class DanjianivActivity : BaseActivity(), View.OnClickListener {
    private val TAG = "DanjuivActivity"
    // 初始化图片资源
    lateinit var bitmap: Bitmap
    internal var width: Int = 0
    internal var height: Int = 0
    // 记录当前的缩放比
    internal var currentScale = 1f
    internal var mwidth: Int = 0
    var code = 0
    var xiangce = 0
    var url = ""
    private var id: Int = 0
    var intgui = -1
    lateinit var listguimingxi: ArrayList<ProdyctionClientBean.guimingxi>
    var guimingxi = false
    private val a = "DanjianivActivity"
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_danjuiv
    }

    override fun initCreate() {
        mwidth = sp.getInt("width", 0)
        val intent = intent
        url = intent.getStringExtra("url")
        code = intent.getIntExtra("code", code)
        xiangce = intent.getIntExtra("xiangce", xiangce)
        getImage1(url)
        if (code == 1 || code == 2) {
            LlPaizhao.visibility = View.VISIBLE
            TvQueding.setOnClickListener(this)
            TvChongpai.setOnClickListener(this)
        }
        if(xiangce == 1){
            TvChongpai.text = "重选"
        }
        IvDanju.setOnTouchListener(TouchListener())
        if (code == 2) {
            listguimingxi = FragmentClientfive.getguimingxi()
            guimingxi=true
        }
        tv_header_title.text = "查看照片"
        iv_header_left.visibility = View.VISIBLE
        iv_header_left.setOnClickListener(this)
        if (code == 2 && listguimingxi.size != 0) {
            id = intent.getIntExtra("id", -1)
            for (i in listguimingxi.indices) {
                if (id.toString() + "" == listguimingxi[i].id) {
                    intgui = i
                }
            }
            tv_header_right.visibility = View.VISIBLE
            tv_header_right.text = "修改"
            tv_header_right.setOnClickListener(this)
        }
    }
    fun XGDialog() {
        val dialog = AlertDialog.Builder(this).create()
        dialog.show()
        dialog.setContentView(R.layout.dialog_xz_gui)
        val lvxg = dialog.findViewById<View>(R.id.lv_XuanGui) as ListView
        val tvno = dialog.findViewById<View>(R.id.tv_no) as TextView
        val adapter = XGAdapter(this@DanjianivActivity, listguimingxi, intgui)
        lvxg.adapter = adapter
        tvno.setOnClickListener { dialog.dismiss() }
        lvxg.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            intgui = position
            val intent = Intent()
            intent.putExtra(CameraActivity.CAMERA_PATH_VALUE2, url)
            intent.putExtra("code", code)
            intent.putExtra("cid", listguimingxi[intgui])
            setResult(Activity.RESULT_OK, intent)
            this@DanjianivActivity.finish()
        }
    }

    fun getImage1(url: String) {

        val updatedialog = Myutil.showupdatedialog(this@DanjianivActivity, "正在加载", false)
        val options: ImageOptions
        if (url.indexOf("https") != -1) {
            options = ImageOptions.Builder().setFadeIn(true).setParamsBuilder(Httputil.getop(this@DanjianivActivity)).build()
        } else {
            options = ImageOptions.Builder().setFadeIn(true).setParamsBuilder(Httputil.getop(this@DanjianivActivity)).build()
        }
        val process = PhotoProcess()
        process.seturl(url)
        //        x.image().bind(imageView,url,options);
        x.image().loadDrawable(process.getUrl(false), options, object : Callback.CacheCallback<Drawable> {
            override fun onCache(result: Drawable): Boolean {
                updatedialog.dismiss()
                val bd = result as BitmapDrawable
                bitmap = bd.bitmap

                //                bitmap = BitmapFactory.decodeFile(result.toString());
                // 获得位图的宽
                width = bitmap.width
                //         获得位图的高
                height = bitmap.height
                // 设置 ImageView初始化显示的图片
                IvDanju.setImageBitmap(bitmap)
                return true
            }

            override fun onSuccess(result: Drawable) {
                updatedialog.dismiss()
                val bd = result as BitmapDrawable
                bitmap = bd.bitmap

                //                bitmap = BitmapFactory.decodeFile(result.toString());
                // 获得位图的宽
                width = bitmap.width
                //         获得位图的高
                height = bitmap.height
                // 设置 ImageView初始化显示的图片
                IvDanju.setImageBitmap(bitmap)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                updatedialog.dismiss()
            }

            override fun onCancelled(cex: Callback.CancelledException) {

            }

            override fun onFinished() {

            }
        })

    }

    override fun onClick(v: View) {
        when (v) {
            TvQueding -> {
                if (!guimingxi) {
                    val intent = Intent()
                    intent.putExtra(CameraActivity.CAMERA_PATH_VALUE2, url)
                    setResult(Activity.RESULT_OK, intent)
                } else {
                    if (listguimingxi.size == 0) {
                        val intent = Intent()
                        intent.putExtra(CameraActivity.CAMERA_PATH_VALUE2, url)
                        intent.putExtra("cid", ProdyctionClientBean.guimingxi())
                        intent.putExtra("code", code)
                        setResult(Activity.RESULT_OK, intent)
                    } else {
                        if (intgui == -1) {
                            XGDialog()
                            return
                        }

                        val intent = Intent()
                        intent.putExtra(CameraActivity.CAMERA_PATH_VALUE2, url)
                        intent.putExtra("code", code)
                        intent.putExtra("cid", listguimingxi[intgui])
                        setResult(Activity.RESULT_OK, intent)
                    }
                }
                finish()
            }
            TvChongpai -> {
                val intent1 = Intent()
                intent1.putExtra(CameraActivity.CAMERA_PATH_VALUE2, url)
                setResult(Activity.RESULT_CANCELED, intent1)
                finish()
            }
            tv_header_right -> XGDialog()
            iv_header_left -> finish()
        }
    }


    private inner class TouchListener : View.OnTouchListener {
        /**
         * 拖拉照片模式
         */
        private val MODE_DRAG = 1
        /**
         * 放大缩小照片模式
         */
        private val MODE_ZOOM = 2
        /**
         * 记录是拖拉照片模式还是放大缩小照片模式
         */
        private var mode = 0// 初始状态

        /**
         * 用于记录开始时候的坐标位置
         */
        private val startPoint = PointF()
        /**
         * 用于记录拖拉图片移动的坐标位置
         */
        private val matrix = Matrix()
        /**
         * 用于记录图片要进行拖拉时候的坐标位置
         */
        private val currentMatrix = Matrix()
        /**
         * 两个手指的开始距离
         */
        private var startDis: Float = 0.toFloat()
        /**
         * 两个手指的中间点
         */
        private var midPoint: PointF? = null

        override fun onTouch(v: View, event: MotionEvent): Boolean {
            /** 通过与运算保留最后八位 MotionEvent.ACTION_MASK = 255  */
            when (event.action and MotionEvent.ACTION_MASK) {
                // 手指压下屏幕
                MotionEvent.ACTION_DOWN -> {
                    mode = MODE_DRAG
                    // 记录ImageView当前的移动位置
                    currentMatrix.set(IvDanju.imageMatrix)
                    startPoint.set(event.x, event.y)
                }
                // 手指在屏幕上移动，改事件会被不断触发
                MotionEvent.ACTION_MOVE ->
                    // 拖拉图片
                    if (mode == MODE_DRAG) {
                        val dx = event.x - startPoint.x // 得到x轴的移动距离
                        val dy = event.y - startPoint.y // 得到x轴的移动距离
                        // 在没有移动之前的位置上进行移动
                        matrix.set(currentMatrix)
                        matrix.postTranslate(dx, dy)
                    } else if (mode == MODE_ZOOM) {
                        val endDis = distance(event)// 结束距离
                        if (endDis > 10f) { // 两个手指并拢在一起的时候像素大于10
                            val scale = endDis / startDis// 得到缩放倍数
                            if (IvDanju.width > mwidth / 2) {
                                val values = FloatArray(9)
                                matrix.getValues(values)
                                if (scale < 1 && values[0] > 0.2) {
                                    matrix.set(currentMatrix)
                                    matrix.postScale(scale, scale, midPoint!!.x, midPoint!!.y)
                                } else if (scale >= 1 && values[0] < 5) {
                                    matrix.set(currentMatrix)
                                    matrix.postScale(scale, scale, midPoint!!.x, midPoint!!.y)
                                }
                            }
                        }
                    }// 放大缩小图片
                // 手指离开屏幕
                MotionEvent.ACTION_UP,
                    // 当触点离开屏幕，但是屏幕上还有触点(手指)
                MotionEvent.ACTION_POINTER_UP -> mode = 0
                // 当屏幕上已经有触点(手指)，再有一个触点压下屏幕
                MotionEvent.ACTION_POINTER_DOWN -> {
                    mode = MODE_ZOOM
                    /** 计算两个手指间的距离  */
                    startDis = distance(event)
                    /** 计算两个手指间的中间点  */
                    if (startDis > 10f) { // 两个手指并拢在一起的时候像素大于10
                        midPoint = mid(event)
                        //记录当前ImageView的缩放倍数
                        currentMatrix.set(IvDanju.imageMatrix)
                    }
                }
            }
            IvDanju.imageMatrix = matrix
            return true
        }

        /**
         * 计算两个手指间的距离
         */
        private fun distance(event: MotionEvent): Float {
            val dx = event.getX(1) - event.getX(0)
            val dy = event.getY(1) - event.getY(0)
            /** 使用勾股定理返回两点之间的距离  */

            return Math.sqrt((dx * dx + dy * dy).toDouble()).toFloat()
        }

        /**
         * 计算两个手指间的中间点
         */
        private fun mid(event: MotionEvent): PointF {
            val midX = (event.getX(1) + event.getX(0)) / 2
            val midY = (event.getY(1) + event.getY(0)) / 2
            return PointF(midX, midY)
        }

    }
}
